package com.manager.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.lang.reflect.Method;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * 分割与合并功能均支持大文件操作
 * */
public class LargeFileUtils {

    public static int fileSplitSize = 512;

    private static Logger logger = LoggerFactory.getLogger(LargeFileUtils.class);

    public static boolean mergePartFile(String dirPath,String mergeFilePath, boolean isDeleteTempFile) throws Exception{
        File resultFile = new File(mergeFilePath);
        if(resultFile.exists()){
            resultFile.delete();
        }
        File tempDirFile = new File(dirPath);
        List<File> fileList = Arrays.asList(tempDirFile.listFiles());
        if(fileList.size() <= 0){
            tempDirFile.delete();
            return false;
        }
        fileList.sort(new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                int o1Index = Integer.valueOf(o1.getName().split("_")[0]);
                int o2Index = Integer.valueOf(o2.getName().split("_")[0]);

                return o1Index - o2Index;
            }
        });
        resultFile.getParentFile().mkdirs();
        resultFile.createNewFile();
        FileChannel resultChannel = new FileOutputStream(resultFile, true).getChannel();
        int i = 0;
        for(File e: fileList){
            FileChannel tempFc = new FileInputStream(e).getChannel();
            resultChannel.transferFrom(tempFc, resultChannel.size(), tempFc.size());
            tempFc.close();
            i++;
            if(isDeleteTempFile){
                e.delete();
            }
            logger.info("total: {}, current: {}, lastModifyDate: {} ", fileList.size(),i,e.lastModified());
        }
        tempDirFile.delete();
        resultChannel.close();
        return true;
    }

    public static String reckonFileSize(long size) {
        DecimalFormat format = new DecimalFormat("0.00");
        String[] s = { "B", "KB", "M", "G" };
        boolean mark = true;
        String res = "";
        int i = 0;
        Double douSize = Double.valueOf(size);
        while (mark) {
            Double temp = douSize / Double.valueOf(1024);
            i += 1;
            if (temp < 1 || i > 3) {
                res = String.valueOf(format.format(temp * Double.valueOf(1024))) + s[i - 1];
                mark = false;
            }
            douSize = temp;
        }

        return res;
    }

    public static void copyFileByPath(String resource,String target) throws IOException{

        FileInputStream filein = null;
        FileOutputStream fileOut = null;

        filein = new FileInputStream(new File(resource));

        File file = new File(target);
        file.getParentFile().mkdirs();
        file.createNewFile();

        fileOut = new FileOutputStream(file);

        FileChannel inChannel = filein.getChannel();
        FileChannel outChanel = fileOut.getChannel();

        inChannel.transferTo(0, inChannel.size(), outChanel);

        filein.close();
        fileOut.close();

        inChannel.close();
        outChanel.close();

    }

    /***
     * 递归删除多级目录中的所有文件与文件夹
     * */
    public static void deleteMultiLevelFiles(String path) {
        File f = new File(path);
        if (!f.exists()) {
            return;
        }
        File[] fs = f.listFiles();
        for (File e : fs) {
            if (e.isDirectory()) {
                deleteMultiLevelFiles(e.getAbsolutePath());
            } else if (e.isFile()) {
                boolean mark = e.delete();
                if (!mark) {
                    System.gc();
                    e.delete();
                }
            }
        }
        boolean mark = f.delete();
        if (!mark) {
            System.gc();
            f.delete();
        }
    }

    public static void main(String[] args) throws Exception {
     //  LargeFileUtils.splitFile("G:\\迅雷下载\\迅雷下载.7z",new SyncClientUdpSplitFileHandler());
     //   LargeFileUtils.splitFile("F:\\music\\Ace组合 - 青花引.mp3",new SyncClientUdpSplitFileHandler());
      //LargeFileUtils.mergePartFile("C:\\Users\\liuhj\\Desktop\\test","C:\\Users\\liuhj\\Desktop\\test","test.7z",true);
//        LargeFileUtils.splitFile("F:\\music\\Alan Walker,Iselin Solheim - Faded.flac", new SplitFileHandler() {
//            @Override
//            public void handle(byte[] data, File reourceFile, int currentSplitIndex, int total, int fileSplitSize) {
//
//            }
//
//            @Override
//            public void success() {
//
//            }
//
//            @Override
//            public void error(Exception e) {
//
//            }
//        });

        System.out.println(2146435072);
        System.out.println(Integer.MAX_VALUE);
    }

}
